from ..forms import BaseForm
from wtforms import StringField,ValidationError,IntegerField
from wtforms.validators import Email,InputRequired,Length,EqualTo,Regexp
from utils import zlcache

# 注册页面表单验证
class SignupFrom(BaseForm):
    email = StringField(validators=[Email(message='请输入正确的邮箱格式'), InputRequired(message='请输入邮箱')])
    email_captcha = StringField(validators=[Length(min=6,max=6,message='请输入正确长度的验证码')])
    username = StringField(validators=[InputRequired(message="请输入用户名")])
    password1 = StringField(validators=[Regexp(r"[0-9a-zA-Z_\.]{6,20}",message="请输入正确格式的密码")])
    password2 = StringField(validators=[EqualTo("password1",message="两次密码不一致！")])
    graph_captcha = StringField(validators=[Regexp(r"\w{4}",message="请输入正确格式的图形验证码")])

    def validate_email_captcha(self,field):
        email_captcha = field.data
        email = self.email.data
        captcha_cache = zlcache.get(email)
        if not captcha_cache or email_captcha.lower()!= captcha_cache.lower():
            raise ValidationError('邮箱验证码错误')

    def validate_graph_captcha(self,field):
        graph_captcha = field.data
        graph_captcha_mem = zlcache.get(graph_captcha.lower())
        if not graph_captcha_mem:
            return ValidationError("图形验证码错误")

# 登录页面表单验证

class SigninForm(BaseForm):
    email = StringField(validators=[Email(message='请输入正确的邮箱格式'), InputRequired(message='请输入邮箱')])
    password = StringField(validators=[Regexp(r"[0-9a-zA-Z_\.]{6,20}", message="请输入正确格式的密码")])
    remember = StringField()


class AddPostForm(BaseForm):
    title = StringField(validators=[InputRequired(message="请输入标题！")])
    content = StringField(validators=[InputRequired(message="请输入内容！")])
    board_id = IntegerField(validators=[InputRequired(message="请输入板块ID！")])

class AddCommentForm(BaseForm):
    content = StringField(validators=[InputRequired(message="请输入评论内容！")])
    post_id = IntegerField(validators=[InputRequired(message="请输入帖子ID！")])